package com.heba.fragment.home;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.heba.Cfg;
import com.heba.adapter.ContentPagerAdapter;
import com.heba.adapter.ItemHomeListAdapter;
import com.heba.banner.MyViewPager;
import com.heba.banner.ViewPagerFocusView;
import com.heba.bean.article.ItemArticleColumnObject;
import com.heba.bean.article.ItemArticleObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.fragment.LazyFragment;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页文章内容界面
 * <p>
 * Created by jason on 2019/2/13.
 */

public class ContentFragment extends LazyFragment {

    private View view;
    private View headerView;
    private SmartRefreshLayout refreshLayout;
    private ListView listView;
    private ItemHomeListAdapter adapter;

    private MyViewPager viewPager;
    private ViewPagerFocusView viewPagerFocusView;

    private ContentPagerAdapter pagerAdapter;

    private String columnID = "";
    private String columnName = "";
    private List<ItemArticleObject> itemArticleObjects = new ArrayList<>();
    private List<ItemArticleObject> topArticleObjects = new ArrayList<>();

    private boolean ifStartLunbo = false;    //判断是否轮播

    /**
     * 实例化fragment
     * 接收activity的参数
     *
     * @param columnObject
     * @return
     */
    public static ContentFragment newInstance(ItemArticleColumnObject columnObject) {
        ContentFragment fragment = new ContentFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.COLUMN_ID, columnObject.getColumnID());
        bundle.putString(CommonConfig.COLUMN_NAME, columnObject.getColumnName());
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        columnID = bundle.getString(CommonConfig.COLUMN_ID, "");
        columnName = bundle.getString(CommonConfig.COLUMN_NAME, "");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void lazyLoad() {
        if (columnName.equals(getResources().getString(R.string.favorite))) {
            getUserArticleData();
        } else {
            getArticleData();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_content, null);
            parseArgument();
            initView(view);
            addHeaderView();
        }
        return view;
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        listView = view.findViewById(R.id.listview);

        adapter = new ItemHomeListAdapter(getActivity(), itemArticleObjects, columnName);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                Page = 1;
                isRefreshFromTop = true;
                if (columnName.equals(getResources().getString(R.string.favorite))) {
                    getUserArticleData();
                } else {
                    getArticleData();
                }
            }
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                Page++;
                isRefreshFromTop = false;
                if (columnName.equals(getResources().getString(R.string.favorite))) {
                    getUserArticleData();
                } else {
                    getArticleData();
                }
            }
        });
    }

    /**
     * addHeaderView
     */
    private void addHeaderView() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.item_home_header, null);
        viewPager = headerView.findViewById(R.id.viewpager);
        viewPagerFocusView = headerView.findViewById(R.id.viewpger_focusview);

        /**
         * viewPager监听
         */
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (!topArticleObjects.isEmpty()) {
                    int currentIndex = position % topArticleObjects.size();
                    viewPagerFocusView.setCurrentIndex(currentIndex);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //设置viewpager图片监听器
        listView.addHeaderView(headerView);
        listView.setAdapter(adapter);
    }

    /**
     * 获取文章数据
     */
    private void getArticleData() {
        if (firstRefresh) {
            firstRefresh = false;
//            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("ColumnID", columnID);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Article/Articlelist", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();

                        /**
                         * 判断是否需要清除数据
                         */
                        if (isRefreshFromTop) {
                            if (!itemArticleObjects.isEmpty()) {
                                itemArticleObjects.clear();
                            }
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }

                        /**
                         * 清除顶部数据，避免重复加载
                         */
                        if (!topArticleObjects.isEmpty())
                            topArticleObjects.clear();

//                        progressDialog.dismiss();
                        try {
                            JSONObject result = new JSONObject(response.trim()).getJSONObject("Result");
                            JSONArray array = result.getJSONArray("ArticleList");
                            JSONArray topArray = result.getJSONArray("TopNews");

                            /**
                             * 加载顶部数据
                             */
                            if (topArray.length() > 0 && columnID.equals("")) {
                                updateTopArticleData(topArray);
                            } else {
                                if (headerView != null) {
                                    listView.removeHeaderView(headerView);
                                }
                            }

                            if (array.length() > 0) {
                                /**
                                 * 加载列表数据
                                 */
                                updateArticleData(array);
                            } else {
                                adapter.notifyDataSetChanged();
//                                ToastShow.displayToast(getActivity(), getResources().getString(R.string.finish_no_data));
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
//                        progressDialog.dismiss();
                        if (isRefreshFromTop) {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }
                    }

                });
    }

    /**
     * updateArticleData
     *
     * @param data
     */
    private void updateArticleData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemArticleObject articleObject = new ItemArticleObject();
                articleObject.setArticleID(object.getString("ArticleID"));
                articleObject.setTitle(object.getString("Title"));
                articleObject.setPublisher(object.getString("Publisher"));
                articleObject.setImageUrl(object.getString("ImageUrl"));
                itemArticleObjects.add(articleObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        adapter.notifyDataSetChanged();
    }

    /**
     * 更新轮播数据
     *
     * @param data
     */
    private void updateTopArticleData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemArticleObject articleObject = new ItemArticleObject();
                articleObject.setArticleID(object.getString("ArticleID"));
                articleObject.setTitle(object.getString("Title"));
                articleObject.setPublisher(object.getString("Publisher"));
                articleObject.setImageUrl(object.getString("ImageUrl"));
                topArticleObjects.add(articleObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新顶部滚动数据
        pagerAdapter = new ContentPagerAdapter(getActivity(), topArticleObjects, columnName);
        viewPager.setAdapter(pagerAdapter);
        if (!topArticleObjects.isEmpty()) {
            //总的点数
            viewPagerFocusView.setCount(topArticleObjects.size(), R.drawable.icon_yuanquan_1, R.drawable.icon_diary_slideshow_s);
            int gbs = 1000 / topArticleObjects.size();
            int totalMax = gbs * topArticleObjects.size();
            viewPager.setCurrentItem(totalMax); // 初始位置在靠近1000的整个整除的数字

            // 当前位置
            int currentIndex = viewPager.getCurrentItem() % topArticleObjects.size();
            viewPagerFocusView.setCurrentIndex(currentIndex);
            startLunbo();
        } else {
            viewPager.setVisibility(View.GONE);
        }
    }

    /**
     * 获取用戶收藏文章
     */
    private void getUserArticleData() {
        if (firstRefresh) {
            firstRefresh = false;
//            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Article/CollectList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();

                        /**
                         * 判断是否需要清除数据
                         */
                        if (isRefreshFromTop) {
                            if (!itemArticleObjects.isEmpty()) {
                                itemArticleObjects.clear();
                            }
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }

//                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (headerView != null) {
                                listView.removeHeaderView(headerView);
                            }
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateUserArticleData(array);
                            } else {
                                adapter.notifyDataSetChanged();
//                                ToastShow.displayToast(getActivity(), getResources().getString(R.string.finish_no_data));
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
//                        progressDialog.dismiss();
                        if (isRefreshFromTop) {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }
                    }

                });
    }

    /**
     * updateAUserrticleData
     *
     * @param data
     */
    private void updateUserArticleData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemArticleObject articleObject = new ItemArticleObject();
                articleObject.setArticleID(object.getString("ArticleID"));
                articleObject.setTitle(object.getString("Title"));
                articleObject.setPublisher(object.getString("Publisher"));
                articleObject.setImageUrl(object.getString("ImageUrl"));
                itemArticleObjects.add(articleObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        adapter.notifyDataSetChanged();

    }

    @Override
    protected void onVisible() {
        super.onVisible();
        if (!topArticleObjects.isEmpty())
            startLunbo();
    }

    @Override
    protected void onHidden() {
        super.onHidden();
        if (!topArticleObjects.isEmpty())
            pauseLunbo();
    }

    /**
     * 停止轮播
     */
    public void pauseLunbo() {
        if (viewPager != null && ifStartLunbo) {
            viewPager.stopTimer();
            ifStartLunbo = false;
        }
    }

    /**
     * 开始轮播
     */
    public void startLunbo() {
        if (viewPager != null && !ifStartLunbo) {
            viewPager.startTimer();
            ifStartLunbo = true;
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        if (event.getEvent().equals(CommonConfig.SCROLL_TO_TOP)) {
          listView.setSelection(0);
        }
    }

}
